package com.wgod.demo.common.utils;

import com.google.common.base.Preconditions;
import com.google.common.io.Files;

import com.wgod.demo.business.entity.AttAchEntity;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.UUID;

/**
 * @author WGod 2018/3/14
 */
public class UploadFileUtil {

    /**
     * 上传附件
     *
     * @param attachment 附件实体
     * @param file       上传文件
     * @param exts       允许上传文件类型
     * @throws IOException 文件输出异常
     */
    public static boolean UploadAttachment(AttAchEntity attachment, MultipartFile file, List<String> exts) throws IOException {
        Preconditions.checkNotNull(file);
        // 获取物理路径
        final String now = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"));
        String targetDirectory = "D:\\upload\\" + now + "\\";
        String tmpFileName = file.getOriginalFilename(); // 上传的文件名
        String ext = Files.getFileExtension(tmpFileName);  //文件后缀名
//        attachment.setName(tmpFileName);
//        attachment.setFileSize(file.getSize());
        // 重命名上传的文件名
        String targetFileName = UUID.randomUUID().toString().replace("-", "") + "." + ext;
        // 其他文件格式不处理
        if (exts.contains(ext)) {
            // 保存的新文件
            File target = new File(targetDirectory, targetFileName);
            if (!target.exists()) {
                //先得到文件的上级目录，并创建上级目录，再创建文件
                target.getParentFile().mkdir();
                //创建文件
                target.createNewFile();
                // 保存文件
                InputStream in = file.getInputStream();
                byte[] buffer = new byte[1024];
                int len = 0;
                tmpFileName = targetDirectory + targetFileName;//文件最终上传的位置
                OutputStream out = new FileOutputStream(tmpFileName);
                while ((len = in.read(buffer)) != -1) {
                    out.write(buffer, 0, len);
                }
                out.close();
                in.close();
            }
//            attachment.setUrl(tmpFileName);
            return true;
        } else {
            return false;
        }
    }

    /**
     * 附件下载
     *
     * @param attachment 文件物理地址
     * @param response   HttpServletResponse
     * @throws IOException 文件读取异常
     */
    public static void DownloadAttachment(AttAchEntity attachment, HttpServletRequest request, HttpServletResponse response) throws IOException {

//        String userAgent = request.getHeader("User-Agent");
//        String fileName = attachment.getName();
//
//        // 针对IE或者以IE为内核的浏览器：
//        if (userAgent.contains("MSIE") || userAgent.contains("Trident")) {
//            fileName = java.net.URLEncoder.encode(fileName, "UTF-8");
//        } else {
//            // 非IE浏览器的处理：
//            fileName = new String(fileName.getBytes("UTF-8"), "ISO-8859-1");
//        }
//
//        response.setHeader("content-type", "application/octet-stream");
//        response.setContentType("application/octet-stream");
//        response.setHeader("Content-Disposition", String.format("attachment; filename=\"%s\"", fileName));
//        response.setCharacterEncoding("UTF-8");
//
//        try(OutputStream os = response.getOutputStream()) {
//            os.write(Files.toByteArray(new File(attachment.getUrl())));
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
    }

}